<template>
	<div>
        <m-pay :money="orderMoney" :payClick="payClick" :goBack="goBack"></m-pay>
	</div>
</template>

<script>
    import Pay from "../../../real-components/Pay";
    import {mapGetters} from "vuex";
    import getOrderInfo from "../../../api/gw/getOrderInfo";
    import {showLoading, hideLoading} from "../../../utils/loading.js";
    import axios from "axios";
    import * as api from "../../../api/gw/index.js";
    import md5 from "js-md5";
    import {Toast} from "../../../utils/toast";
	export default {
		props: {
			pageType: {
				type: String,
				default: "android"
			}
		},
		data() {
			return {
                orderMoney: 0,
                // orderType: 2,//默认为2，跳到订单列表的待配送状态
                payClick: () => {}
            }
		},
		computed: {
            orderNo() {
                // return this.$route.query
                // console.log(this.$route);
                return this.$route.params.orderNo;
            },
            //订单类型，线上订单为2（跳转到待配送），线下订单为1（跳转到全部）
            orderType() {
                return this.$route.params.orderType ? this.$route.params.orderType : 2;
            }

        },
        methods: {
            init() {
                // let script = document.createElement("script");
                // script.setAttribute("src", "static/script/cordova/android/cordova.js");
                // document.body.appendChild(script);
                // script.onload = () => {
                    // console.log("cordova脚本加载成功");
                    var that = this;
                    var pay_no = '';
                    var created_ts = '';
                    var se_sign = '';
                    var use_json = '0';
                    var amount = ''
                    var SEPayPlugin_Start = function (pay_no,created_ts,se_sign,amount){
                        //alert("start to pay 1. ");
                        //初始化
                        cordova.require('cordova/channel').onCordovaReady.subscribe(function() {
                            //  在安卓 进入后 在注册这个方法的时候 和安卓那边就已经调用这个方法了；
                            //alert("start to pay 2, exec SEPayPlugin  ");
                            cordova.exec(null, null, 'SEPayPlugin',null, []);
                            //CenterCommandPlugin('start');
                            doPay(pay_no,created_ts,se_sign,amount);
                        });
                    }
                    var doPay = function  (pay_no,created_ts,se_sign,amount){ 
                        var data = {
                            pay_no: pay_no,
                            created_ts: created_ts,
                            se_sign: se_sign,
                            use_json: '0',
                            order_money: amount
                        }
                        var pay = "sePay" + JSON.stringify(data)
                            SEPayPlugin(pay,
                                function(){
                                    // setTimeout(() => {
                                        console.log("支付回调", "支付成功");
                                        that.$router.replace({"name": "paysuccessfully", params: {orderType: that.orderType}});
                                    // }, 1000);
                                },
                                function (){
                                    console.log("支付失败");
                                    Toast({
                                        message: '支付失败',
                                        type: "fail",
                                        duration: 1000
                                    });
                            });
                    }
                    var SEPayPlugin =  function  (params,sucFunc,failFunc,opts, className) {
                        var params = params || null;
                        var sucFunc = sucFunc || function(){};
                        var failFunc = failFunc || function(){};
                        var opts = opts || {};
                        var className = className || null ;
                        
                        try{
                            console.log("11111111");
                            cordova.exec(sucFunc,failFunc, "SEPayPlugin", "doPay", [className, params,opts]) ;
                        }
                        catch(err){
                            alert("如您在app中进行支付，程序调起支付app失败，请点击按钮手动尝试下！")
                        }
                    }

                    // this.$refs.pay.onclick = function() {
                    this.payClick = function() {
//                      console.log("这里在执行");
//                      console.log("+++++++++++++++++", that.orderMoney);
						let callback = () => {
							//如果实付金额为0，则直接跳到支付成功页面
	                        if (that.orderMoney > 0) {
	                            // 请求java接口，请求前判断用户使用余额情况 判断是否需要调起翌支付
	                            var sessionId = localStorage.getItem('sessionId');
	                            //订单编号
	                            var orderNo = that.orderNo;
	                            //
	                            var scenary_id = "3";
	                            let options = {
	                                method: "post",
	                                // url: window.api.local_host + api.gwPay,
	                                url: window.api.trade_host + api.gwPay,
	                                data: {
	                                    sessionId,
	                                    "bill_id": orderNo,
	                                    scenary_id
	                                }
	                            }
	                            axios(options).then(data => {
	                                // console.log(data);
	                                if (data.status === 200) {
	                                    var listData = data.data.data[0];
	                                    if(listData != null){
	                                        var pay_no = listData.pay_no;  //
	                                        var app_code = listData.app_code;
	                                        var se_payment_code = listData.se_payment_code;
	                                        var se_private_key = listData.se_private_key;
	                                        var created_ts = Date.parse(new Date())/1000;  //
	                                        var amount = listData.amount;
	                                        var appStr = app_code + se_payment_code + pay_no + created_ts;
	                                        var semd5 = md5(appStr) + se_private_key;
	                                        var se_sign = md5(semd5); //
	                                        //alert("开始支付,pay_no="+pay_no+"\r\nse_payment_code="+se_payment_code+
	                                        //		"\r\nse_private_key="+se_private_key+"\r\n");
	                                        SEPayPlugin_Start(pay_no,created_ts,se_sign,amount)
	                                    }else{
	                                        alert("请求支付失败");
	                                    }
	                                }
	                            });
	                        } else if (that.orderMoney === 0) {
	                            console.log("这里在执行");
	                            that.$router.replace({"name": "paysuccessfully", params: {orderType: that.orderType}});
	                        } else if (that.orderMoney === "fail") {
	                            Toast({
	                                message: '订单信息失效',
	                                type: "fail",
	                                duration: 1000
	                            });
	                            return;
	                        }
						}
						
						that.getTimeRight(callback);
                        
                    }
                // }
                // document.body.appendChild(script);
            },
            getOrderInfoFromApi() {
                showLoading();
                if (this.orderNo) {
                    let callback = data => {
                        console.log(data);
                        console.log("-------------------", data.realPay);
                        this.orderMoney = parseFloat(data.realPay);
                        this.orderType = 2;
                        this.init();
                        hideLoading();
                    }
                    //获取订单信息失败的回调
                    let errFn = () => {
                        this.orderMoney = "fail";
                        hideLoading();
                    }
                    getOrderInfo(this.orderNo, callback, errFn);
                } else {
                    hideLoading();
                    //跳回个人中心
                    this.$router.replace("profile");
                    
                }
            },
            goBack() {
                // 跳转到待支付页面
                this.$router.replace({"name": "order", query: {orderStatus: 1}});
            },
            //判断是否在可配送时间内
            getTimeRight(callback){
				console.log("ooo");
//				let url = window.api.local_host + '/orderDeliveryPool/checkCanToPay/' + this.orderNo;
				let url = window.api.trade_host + '/orderDeliveryPool/checkCanToPay/' + this.orderNo;
				var sessionId = localStorage.getItem('sessionId');
				console.log(url,'链接地址')
				let config = {
	            	url:url,
	            	method: 'GET',
	            	headers: {'sessionId': sessionId},
	            };
	            axios(config).then((res) => {
	            	console.log(res.data.returncode,'返回参数');
	            	if(res.data.returnCode === 0){
						this.$router.push({name:'changeOrderTime',query:{orderNo:this.orderNo}});
	            	} else if (res.data.returnCode === 1) {
	            		callback && callback();
	            	}
	            })
	        }
        },
		components: {
			"m-pay": Pay
        },
        created() {
               console.log("1234567", this.$route.params.orderNo);
            this.getOrderInfoFromApi();
            // console.log("gwPay", gwPay);

        }
	}
</script>

<style>
</style>